<template>
	<view class="container">
		<!-- 文章标题 -->
		<view class="title-input">
			<input v-model="articleTitle" placeholder="请输入文章标题" maxlength="50" />
		</view>

		<!-- 年级选择 -->
		<view class="grade-selection">
			<text class="label">适用年级：</text>
			<view class="grade-buttons">
				<button v-for="grade in gradeOptions" :key="grade.value"
					:class="['grade-btn', { 'active': selectedGrades.includes(grade.value) }]"
					@click="toggleGrade(grade.value)">
					{{ grade.label }}
				</button>
			</view>
		</view>

		<!-- 视频上传区域 -->
		<view class="upload-section">
			<view class="section-title">
				<text>视频上传</text>
				<text class="tips">(最多{{maxVideoCount}}个视频)</text>
			</view>
			<view class="video-preview-list">
				<view class="video-preview-item" v-for="(video, index) in videoList" :key="index">
					<video :src="video.src" controls class="preview-video"></video>
					<view class="remove-btn" @click="removeVideo(index)">
						<uni-icons type="closeempty" color="#fff" size="18"></uni-icons>
					</view>
					<view class="video-info">
						<text>{{ getFileName(video.src) }}</text>
						<text>{{ formatFileSize(video.file.size) }}</text>
					</view>
				</view>
			</view>
			<button class="upload-btn" @click="chooseVideo" :disabled="videoList.length >= maxVideoCount">
				<uni-icons type="plusempty" size="20" color="#07c160"></uni-icons>
				<text>添加视频</text>
			</button>
		</view>

		<!-- 富文本编辑器 -->
		<view class="editor-section">
			<view class="section-title">
				<text>文章内容</text>
			</view>
			<view class="editor-box">
				<sp-editor :toolbar-config="{
          excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
          iconSize: '18px'
        }" @init="initEditor" @input="inputOver" @upinImage="upinImage" @overMax="overMax" @addLink="addLink"
					@exportHtml="exportHtml"></sp-editor>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="button-group">
			<button class="back-button" @click="goBack">返回</button>
			<button class="publish-button" @click="publishArticle">发布文章</button>
		</view>

		<!-- 上传进度弹窗 -->
		<uni-popup ref="progressPopup" type="center" :mask-click="false">
			<view class="progress-popup">
				<view class="popup-title">上传进度</view>
				<view class="progress-list">
					<view class="progress-item" v-for="(item, index) in uploadProgress" :key="index">
						<view class="file-info">
							<text class="file-name">{{ getFileName(item.filePath) }}</text>
							<text class="progress-percent">{{ item.progress }}%</text>
						</view>
						<progress class="progress-bar" :percent="item.progress" show-info stroke-width="3" />
						<view class="status-info">
							<text class="status-text" :class="{
                'uploading': item.status === 'uploading',
                'success': item.status === 'success',
                'error': item.status === 'error'
              }">
								{{ getStatusText(item.status) }}
							</text>
							<uni-icons v-if="item.status === 'success'" type="checkmarkempty" color="#07c160"
								size="18"></uni-icons>
							<uni-icons v-if="item.status === 'error'" type="closeempty" color="#dd524d"
								size="18"></uni-icons>
						</view>
					</view>
				</view>
				<view class="popup-footer">
					<button class="confirm-btn" :disabled="!uploadComplete" @click="closeProgressPopup">完成</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				id: 0,
				editorIns: null,
				articleTitle: '',
				tempImages: [],
				selectedGrades: [],
				uploadProgress: [],
				uploadComplete: false,

				// 视频相关
				videoList: [],
				maxVideoCount: 3,

				gradeOptions: [{
						value: '一年级',
						label: '一年级'
					},
					{
						value: '二年级',
						label: '二年级'
					},
					{
						value: '三年级',
						label: '三年级'
					},
					{
						value: '四年级',
						label: '四年级'
					},
					{
						value: '五年级',
						label: '五年级'
					},
					{
						value: '六年级',
						label: '六年级'
					},
					{
						value: '七年级',
						label: '七年级'
					},
					{
						value: '八年级',
						label: '八年级'
					},
					{
						value: '九年级',
						label: '九年级'
					},
					{
						value: '高一',
						label: '高一'
					}
				]
			}
		},

		onLoad() {
			this.getLastId();
		},

		methods: {
			// 获取文章ID
			getLastId() {
				uni.request({
					url: globalVariable._value + "/getLastId",
					method: "get",
					success: (res) => {
						let info = res.data;
						if (info.status == 1) {
							this.id = info.data;
						}
					}
				})
			},

			// 选择视频
			chooseVideo() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					compressed: true,
					success: (res) => {
						const videoItem = {
							src: res.tempFilePath,
							file: res,
							uploadStatus: 'waiting'
						};
						this.videoList.push(videoItem);

						// 添加到上传进度列表
						this.uploadProgress.push({
							filePath: res.tempFilePath,
							progress: 0,
							status: 'waiting',
							type: 'video'
						});

						uni.showToast({
							title: '视频已添加',
							icon: 'success'
						});
					},
					fail: (err) => {
						uni.showToast({
							title: '选择视频失败',
							icon: 'none'
						});
					}
				});
			},

			// 移除视频
			removeVideo(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个视频吗？',
					success: (res) => {
						if (res.confirm) {
							// 从视频列表中移除
							const removedVideo = this.videoList.splice(index, 1)[0];

							// 从上传进度列表中移除对应的视频
							this.uploadProgress = this.uploadProgress.filter(
								item => item.filePath !== removedVideo.src
							);
						}
					}
				});
			},

			// 格式化文件大小
			formatFileSize(bytes) {
				if (bytes === 0) return '0 B';
				const k = 1024;
				const sizes = ['B', 'KB', 'MB', 'GB'];
				const i = Math.floor(Math.log(bytes) / Math.log(k));
				return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
			},

			// 上传所有文件
			async uploadAllFiles() {
				// 先上传图片
				if (this.tempImages.length > 0) {
					await this.uploadAllImages();
				}

				// 再上传视频
				if (this.videoList.length > 0) {
					await this.uploadAllVideos();
				}

				this.uploadComplete = true;
			},

			// 上传所有视频
			uploadAllVideos() {
				return Promise.all(
					this.videoList.map((video, index) => {
						if (video.uploadStatus === 'success') {
							return Promise.resolve();
						}

						return new Promise((resolve, reject) => {
							const videoIndex = this.uploadProgress.findIndex(
								item => item.filePath === video.src
							);

							if (videoIndex === -1) {
								reject(new Error('找不到视频上传进度'));
								return;
							}

							const uploadTask = uni.uploadFile({
								url: globalVariable._value + '/uploadVideo',
								filePath: video.file.tempFilePath,
								name: 'video',
								formData: {
									id: this.id,
									index: index
								},
								success: (res) => {
									const info = JSON.parse(res.data);
									if (info.status == 1) {
										this.updateProgress(videoIndex, 100, 'success');
										video.uploadStatus = 'success';
										resolve();
									} else {
										this.updateProgress(videoIndex, 100, 'error');
										video.uploadStatus = 'error';
										reject(new Error('视频上传失败'));
									}
								},
								fail: (err) => {
									this.updateProgress(videoIndex, 100, 'error');
									video.uploadStatus = 'error';
									reject(err);
								}
							});

							uploadTask.onProgressUpdate((res) => {
								this.updateProgress(videoIndex, res.progress, 'uploading');
							});
						});
					})
				);
			},

			// 发布文章
			async publishArticle() {
				if (!this.articleTitle.trim()) {
					uni.showToast({
						title: '请输入文章标题',
						icon: 'none'
					});
					return;
				}

				if (this.selectedGrades.length === 0) {
					uni.showToast({
						title: '请选择适用年级',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '准备上传中...',
					mask: true
				});

				try {
					const editorContent = await this.getEditorContent();
					const articleData = {
						id: this.id,
						title: this.articleTitle,
						article: editorContent.html,
						role: this.selectedGrades.join('@'),
						hasVideo: this.videoList.length > 0,
						videoCount: this.videoList.length
					};

					// 先上传文章内容
					await this.submitArticle(articleData);

					// 如果有文件需要上传
					if (this.tempImages.length > 0 || this.videoList.length > 0) {
						uni.hideLoading();
						this.initUploadProgress();
						await this.uploadAllFiles();
						this.uploadComplete = true;
						uni.showToast({
							title: '所有文件上传完成',
							icon: 'success'
						});
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '发布失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('发布文章失败:', error);
				}
			},

			// 以下是原有方法保持不变
			inputOver(e) {
				console.log('==== inputOver :', e)
			},
			overMax(e) {
				console.log('==== overMax :', e)
			},
			initEditor(editor) {
				this.editorIns = editor;
				this.preRender()
			},
			preRender() {},

			async upinImage(tempFiles, editorCtx) {
				try {
					const insertTasks = tempFiles.map(item => {
						const filePath = item.path || item.tempFilePath;
						this.tempImages.push(filePath);
						return new Promise(resolve => {
							editorCtx.insertImage({
								src: filePath,
								width: '80%',
								success: () => resolve()
							});
						});
					});
					await Promise.all(insertTasks);
				} catch (error) {
					console.error('插入图片失败:', error);
				}
			},

			exportHtml(e) {
				uni.navigateTo({
					url: '/pages/out/out',
					success(res) {
						res.eventChannel.emit('e-transmit-html', {
							data: e
						});
					}
				});
			},

			addLink(e) {
				console.log('==== addLink :', e)
			},
			goBack() {
				uni.navigateBack()
			},

			toggleGrade(grade) {
				const index = this.selectedGrades.indexOf(grade);
				if (index === -1) {
					this.selectedGrades.push(grade);
				} else {
					this.selectedGrades.splice(index, 1);
				}
			},

			getFileName(filePath) {
				return filePath.split('/').pop();
			},

			getStatusText(status) {
				const statusMap = {
					'uploading': '上传中',
					'success': '上传成功',
					'error': '上传失败'
				};
				return statusMap[status] || '';
			},

			initUploadProgress() {
				// 初始化图片上传进度
				const imageProgress = this.tempImages.map(filePath => ({
					filePath,
					progress: 0,
					status: 'uploading',
					type: 'image'
				}));

				// 初始化视频上传进度
				const videoProgress = this.videoList.map(video => ({
					filePath: video.src,
					progress: 0,
					status: 'uploading',
					type: 'video'
				}));

				this.uploadProgress = [...imageProgress, ...videoProgress];
				this.uploadComplete = false;
				this.$refs.progressPopup.open();
			},

			closeProgressPopup() {
				this.$refs.progressPopup.close();
				this.uploadProgress = [];
				this.tempImages = [];
				this.videoList = [];
				setTimeout(() => {
					uni.navigateBack();
				}, 500);
			},

			getEditorContent() {
				return new Promise((resolve) => {
					this.editorIns.getContents({
						success: (res) => {
							resolve(res)
						}
					});
				});
			},

			uploadAllImages() {
				return Promise.all(
					this.tempImages.map((filePath, index) => {
						return new Promise((resolve, reject) => {
							const uploadTask = uni.uploadFile({
								url: globalVariable._value + '/uploadImage',
								filePath: filePath,
								name: 'file',
								formData: {
									id: this.id
								},
								success: (res) => {
									const info = JSON.parse(res.data);
									if (info.status == 1) {
										this.updateProgress(index, 100, 'success');
										resolve();
									} else {
										this.updateProgress(index, 100, 'error');
										reject(new Error('图片上传失败'));
									}
								},
								fail: (err) => {
									this.updateProgress(index, 100, 'error');
									reject(err);
								}
							});

							uploadTask.onProgressUpdate((res) => {
								this.updateProgress(index, res.progress, 'uploading');
							});
						});
					})
				);
			},

			updateProgress(index, progress, status) {
				this.$set(this.uploadProgress, index, {
					...this.uploadProgress[index],
					progress,
					status
				});
			},

			submitArticle(data) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: globalVariable._value + '/uploadArticle',
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						data: JSON.stringify(data),
						success: (res) => {
							let info = res.data;
							if (info.status == 1) {
								resolve(res.data);
							} else {
								reject(new Error(info.message || '文章上传失败'));
							}
						},
						fail: (err) => {
							reject(err)
						}
					});
				});
			}
		}
	}
</script>
<style>
	.container {
		padding: 20rpx;
		padding-bottom: 160rpx;
		background-color: #f8f8f8;
	}

	/* 标题输入 */
	.title-input {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.title-input input {
		width: 100%;
		height: 80rpx;
		padding: 0 20rpx;
		font-size: 32rpx;
	}

	/* 年级选择 */
	.grade-selection {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.grade-selection .label {
		display: block;
		margin-bottom: 15rpx;
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
	}

	.grade-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.grade-btn {
		flex: none;
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 30rpx;
		font-size: 26rpx;
		background-color: #f5f5f5;
		color: #666;
		border-radius: 30rpx;
		margin: 0;
		border: none;
	}

	.grade-btn.active {
		background-color: #07c160;
		color: #fff;
	}

	/* 上传区域 */
	.upload-section {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.section-title .tips {
		font-size: 24rpx;
		color: #999;
		margin-left: 15rpx;
		font-weight: normal;
	}

	/* 视频预览列表 */
	.video-preview-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	.video-preview-item {
		position: relative;
		border-radius: 12rpx;
		overflow: hidden;
		background-color: #f5f5f5;
	}

	.preview-video {
		width: 100%;
		height: 300rpx;
	}

	.remove-btn {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.video-info {
		padding: 15rpx;
		background-color: rgba(0, 0, 0, 0.7);
		color: #fff;
		font-size: 24rpx;
		display: flex;
		justify-content: space-between;
	}

	/* 上传按钮 */
	.upload-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		background-color: #f5f5f5;
		color: #07c160;
		font-size: 28rpx;
		border-radius: 12rpx;
		border: 1px dashed #07c160;
	}

	.upload-btn[disabled] {
		opacity: 0.6;
	}

	.upload-btn text {
		margin-left: 10rpx;
	}

	/* 编辑器区域 */
	.editor-section {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.editor-box {
		min-height: 400rpx;
	}

	/* 底部按钮 */
	.button-group {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.back-button {
		flex: 1;
		margin-right: 20rpx;
		background-color: #f5f5f5;
		color: #666;
		border-radius: 50rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
	}

	.publish-button {
		flex: 1;
		background-color: #07c160;
		color: #fff;
		border-radius: 50rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
	}

	/* 上传进度弹窗 */
	.progress-popup {
		width: 650rpx;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-sizing: border-box;
	}

	.popup-title {
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
		color: #333;
	}

	.progress-list {
		max-height: 70vh;
		overflow-y: auto;
	}

	.progress-item {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 12rpx;
	}

	.file-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 15rpx;
	}

	.file-name {
		font-size: 26rpx;
		color: #555;
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.progress-percent {
		font-size: 26rpx;
		color: #07c160;
		margin-left: 20rpx;
	}

	.progress-bar {
		width: 100%;
	}

	.status-info {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-top: 10rpx;
	}

	.status-text {
		font-size: 24rpx;
		margin-right: 10rpx;
	}

	.status-text.uploading {
		color: #2979ff;
	}

	.status-text.success {
		color: #07c160;
	}

	.status-text.error {
		color: #dd524d;
	}

	.popup-footer {
		margin-top: 30rpx;
		display: flex;
		justify-content: center;
	}

	.confirm-btn {
		width: 200rpx;
		background-color: #07c160;
		color: #fff;
		border-radius: 50rpx;
		height: 70rpx;
		line-height: 70rpx;
	}

	.confirm-btn[disabled] {
		background-color: #f5f5f5;
		color: #999;
	}
</style>